package com.ht.medicaltreatment.viewmodel

import android.Manifest
import android.app.Activity
import androidx.lifecycle.viewModelScope
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions
import com.ht.medicaltreatment.bean.LoginBean
import com.ht.medicaltreatment.view.PermissionSettingDialog
import com.xgst.lib.http.ApiResult
import kotlinx.coroutines.launch

class LoginViewModel : BaseViewModel() {

    fun login(account:String,psw:String,onResult:(LoginBean)->Unit,onError:(String)->Unit){
        viewModelScope.launch {
            val bean = mApi.login(account, psw)
            when(bean){
                is ApiResult.Success -> onResult(bean.data.data!!)
                is ApiResult.Error -> onError(bean.errorMessage)
            }
        }
    }

    fun login(uid:String,onResult:(LoginBean)->Unit,onError:(String)->Unit){
        viewModelScope.launch {
            val bean = mApi.login(uid)
            when(bean){
                is ApiResult.Success -> onResult(bean.data.data!!)
                is ApiResult.Error -> onError(bean.errorMessage)
            }
        }
    }

    fun checkPermission(context: Activity,onGranted:()->Unit){
        XXPermissions.with(context)
            .permission(
                arrayOf(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA,
                )
            )
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>?, all: Boolean) {
                    if (all) {
                        onGranted()
                    }
                }

                override fun onDenied(permissions: MutableList<String>?, never: Boolean) {
                    if (never) {
                        PermissionSettingDialog(context)
                            .show({
                                XXPermissions.startPermissionActivity(
                                    context,
                                    permissions
                                )
                            })
                    }
                }
            })
    }
}
